package api.actions;

import java.awt.Point;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Iterator;

import javax.swing.JFileChooser;

import api.Interface;

public class Guardar {
	public static void run() {
		
		int value = Interface.FileChooser.showSaveDialog(Interface.frame);
		
		if (value == JFileChooser.APPROVE_OPTION) {
			String fichero = Interface.FileChooser.getSelectedFile().getAbsolutePath();
			crearArchivo(fichero);
			
			Interface.mnIni.setEnabled(false);
		}
	}

	private static void crearArchivo(String fich) {
		FileWriter outFile;
		HashSet<Point> obstaculo;
		Point punto;
		try {
			
			outFile = new FileWriter(fich);
			PrintWriter out = new PrintWriter(outFile);
			
			out.println("Fichero que guarda una partida inicializada");
			out.println("");
			out.println("Dimensiones del tablero");
			int n = (int) Interface.getTablero().getN();
			int m = (int) Interface.getTablero().getM();
			out.println("{" + m + "," + n + "}");
			out.println("Posicion inicial:");
			int x = (int) Interface.getTablero().getRobot().getPosInicial().getX();
			int y = (int) Interface.getTablero().getRobot().getPosInicial().getY();
			out.println("{" + x + "," + y + "}");
			out.println("Posicion Final:");
			x = (int) Interface.getTablero().getRobot().getPosFinal().getX();
			y = (int) Interface.getTablero().getRobot().getPosFinal().getY();
			out.println("{" + x + "," + y + "}");
			out.println("OBSTACULOS");
			out.println("Numero:");
			x = (int) Interface.getTablero().getObs().size();
			out.println(x);
			out.println("Posiciones:");
			obstaculo = Interface.getTablero().getObs();
			Iterator<Point> it = obstaculo.iterator();
			while (it.hasNext()) {
				punto = (Point) it.next();
				x = (int) punto.getX();
				y = (int) punto.getY();
				out.println("{" + x + "," + y + "}");
			}

			
			out.flush();
			out.close();
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
